<?php

namespace app\api\model\wanlshop;

use think\Exception;
use think\Model;
use traits\model\SoftDelete;

class Order extends Model
{

    use SoftDelete;

    

    // 表名
    protected $name = 'wanlshop_order';
    
    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'int';

    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';
    protected $deleteTime = 'deletetime';
	
	// 追加属性
	protected $append = [
		'createtime_text',
	    'paymenttime_text',
	    'delivertime_text',
		'taketime_text',
	    'dealtime_text'
	];
	
	protected function setOrderNoAttr($value)
	{
	    return substr(time(),-8).substr(substr(implode(NULL, array_map('ord', str_split(substr(uniqid(), 7, 13), 1))), 0, 8).$value,-8);
	}
	
	protected function getStateAttr($value){
		return intval($value);
	}
	
	
	public function getCreatetimeTextAttr($value, $data)
	{
	    $value = $value ? $value : (isset($data['createtime']) ? $data['createtime'] : '');
	    return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
	}
	
	public function getPaymenttimeTextAttr($value, $data)
	{
	    $value = $value ? $value : (isset($data['paymenttime']) ? $data['paymenttime'] : '');
	    return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
	}
	
	
	public function getDelivertimeTextAttr($value, $data)
	{
	    $value = $value ? $value : (isset($data['delivertime']) ? $data['delivertime'] : '');
	    return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
	}
	
	public function getTaketimeTextAttr($value, $data)
	{
	    $value = $value ? $value : (isset($data['taketime']) ? $data['taketime'] : '');
	    return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
	}
	
	
	public function getDealtimeTextAttr($value, $data)
	{
	    $value = $value ? $value : (isset($data['dealtime']) ? $data['dealtime'] : '');
	    return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
	}

	
	
	
    protected function setPaymenttimeAttr($value)
    {
        return $value === '' ? null : ($value && !is_numeric($value) ? strtotime($value) : $value);
    }

    protected function setDelivertimeAttr($value)
    {
        return $value === '' ? null : ($value && !is_numeric($value) ? strtotime($value) : $value);
    }

    protected function setDealtimeAttr($value)
    {
        return $value === '' ? null : ($value && !is_numeric($value) ? strtotime($value) : $value);
    }
	
	

    public function user()
    {
        return $this->belongsTo('app\common\model\User', 'user_id', 'id', [], 'LEFT')->setEagerlyType(0);
    }
	
	public function pay()
	{
	    return $this->belongsTo('app\api\model\wanlshop\Pay', 'id', 'order_id', [], 'LEFT')->setEagerlyType(0);
	}
	
	// 店铺
	public function shop()
	{
	    return $this->belongsTo('app\api\model\wanlshop\Shop', 'shop_id', 'id', [], 'LEFT')->setEagerlyType(0);
	}
	
	// 快递列表
	public function kuaidi()
	{
	    return $this->belongsTo('app\api\model\wanlshop\Kuaidi', 'express_name', 'code', [], 'LEFT')->setEagerlyType(0);
	}


    // 订单商品
    public function goods()
    {
        return $this->hasMany('app\api\model\wanlshop\OrderGoods', 'order_id', 'id')->order('weight','desc');
    }


    //确认收货,$identity:user=用户收货.否则为店铺id
    public function confirm($id,$identity){

        // 判断权限
        if($identity == 'user'){
            $auth = \app\common\library\Auth::instance();
            $where = ['id' => $id, 'state'=> 3, 'user_id' => $auth->id];
        }else{
            $where = ['id' => $id, 'state'=> 2, 'shop_id' => $identity];
        }

        $order = model('app\api\model\wanlshop\Order')
            ->where($where)
            ->find();
        if(!$order){
            throw new Exception('订单异常');
        }
        $freight = model('app\api\model\wanlshop\ShopFreight')->where('id', $order['freight_id'])->find();
        if($freight['type'] == 'ziti'){
            model('app\api\model\wanlshop\Package')->where([
                'order_id'=>$order['id']
            ])->update([
                'delivery_status' => 1
            ]);
        }
        $packages = model('app\api\model\wanlshop\Package')->where([
            'order_id'=>$order['id']
        ])->select();
        foreach ($packages as $package){
            // 平台转款给商家
            model('app\common\model\wanlshop\Settlement')
                ->putRecord($package['settlement_price'],$order['shop'] ,$order['order_no'],$package['package_no'], '买家确认收货');
        }

        // 查询是否有退款
        $refund = model('app\api\model\wanlshop\Refund')
            ->where(['order_id' => $id, 'state' => 4])
            ->select();
        // 退款存在
        if($refund){
            foreach($refund as $value){
                model('app\common\model\wanlshop\Settlement')->putRecord(-($value['total_goods_price'] - $value['total_supply_price']),$order['shop'] ,$order['order_no'],'', '该订单存在的退款');
            }
        }
        // 更新订单状态
        $res = $order->save(['state' => 4,'taketime' => time()],['id' => $id]);
        if($res){
           return $order;
        }else{
            throw new Exception('订单更新失败');
        }
    }

}
